package com.example.zsr.downloadcontinue.download;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.example.zsr.downloadcontinue.ToolUtils.ContantsUtils;
import com.example.zsr.downloadcontinue.entity.FileInfo;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhengshaorui on 2017/2/22.
 */

public class DownloadService extends Service {
    private static final String TAG = "DownloadService";
    private static final int START_DOWNLOAD = 1;
    private static final int FILE_NOT_FOUND = 2;
    private static Context mContext;
    private Map<String,DownloadTask> mDownloadMap = new LinkedHashMap<String,DownloadTask>();
    private Map<String,FileInfo> mFileInfoTaskMap = new LinkedHashMap<String,FileInfo>();

    private static ExecutorService sExecutor = Executors.newFixedThreadPool(DownloadTaskManger.TaskCount);


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case START_DOWNLOAD:
                    FileInfo fileInfo = (FileInfo) msg.obj;

                    //把下载任务用一个列表保存起来
                   // mDownloadMap.put(fileInfo.getApkurl(),mTask);
                    break;
                case FILE_NOT_FOUND:
                    FileInfo fileerror = (FileInfo) msg.obj;
                    Toast.makeText(mContext,fileerror.getFileName()+" 下载链接错误",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");

        if (fileInfo.getBtnstatus() == ContantsUtils.START){
            if (fileInfo.getFilestatus() == ContantsUtils.FILE_NOT_DOWNLOAD){//如果还未下载
                mFileInfoTaskMap.put(fileInfo.getApkurl(),fileInfo);  //管理起来
            }
            DownloadTask task = mDownloadMap.get(fileInfo.getApkurl());
            if (task != null){
                task.isPause = false;
            }
            getFileLengthThread download = new getFileLengthThread(fileInfo);
            //DownloadManager.sExecutorService.execute(download);
            sExecutor.execute(download);

        }else if(fileInfo.getBtnstatus() == ContantsUtils.PAUSE){
            DownloadTask task = mDownloadMap.get(fileInfo.getApkurl());
            if (task != null){
                task.isPause = true;
            }
        }

        Log.d(TAG, "onStartCommand: "+fileInfo);

        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 启动任务开始下载
     * @param fileInfo
     */
    private synchronized  void startDownloadTask(FileInfo fileInfo){


        DownloadTask mTask = new DownloadTask(mContext,fileInfo.getThreadCount());
        mDownloadMap.put(fileInfo.getApkurl(), mTask);
        mTask.download(fileInfo, DownloadTaskManger.Holder.getInstance().mDownloadCallback);

    }


    /**
     * 启动线程获取文件的大小，然后开启任务下载文件
     */

    class getFileLengthThread extends  Thread{
        public boolean isfinished = false;
        FileInfo fileinfo;
        public getFileLengthThread(FileInfo fileinfo){
            this.fileinfo = fileinfo;
        }
        @Override
        public void run() {
            super.run();
            HttpURLConnection conn = null;
            try {
                URL url = new URL(fileinfo.getApkurl());
                conn = (HttpURLConnection) url.openConnection();
                //加上这句是为了防止connection.getContentLength()获取不到
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                if (conn.getResponseCode() == 200){
                    int length = conn.getContentLength();
                    if (length < 0) return;
                    else fileinfo.setLength(length);
                }

                File dir = new File(fileinfo.getFileDir());
                if (!dir.exists()){
                    dir.mkdir();
                }
                fileinfo.setDir(dir);
                Log.d(TAG, "run: "+ fileinfo);
                isfinished = true;
                startDownloadTask(fileinfo);

               // mHandler.obtainMessage(START_DOWNLOAD,fileinfo).sendToTarget();

            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "error: "+e.toString());

            }finally {
                conn.disconnect();
            }
        }
    }
}
